package com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReviewTestPaper.aibkQuesReviewPPT

import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioPlayer
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import android.animation.ObjectAnimator
import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReviewTestPaper.QuesReviewInforIndexHelp
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReviewTestPaper.QuesReviewInforIndexHelp.getChildListBean
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReviewTestPaper.aibkQuesReviewZHT.QuesReviewFragmentParentPpt
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.adjustAudioSpeedHelp
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TestPaperReviewInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPlayerSpeed.PlayerSpeedChoiceAdapter
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.LancooAnim
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.widget.KWebView
import kotlinx.android.synthetic.main.aibk_include_article_view.view.*
import kotlinx.android.synthetic.main.aibk_include_child_answer_title_infor.view.*
import kotlinx.android.synthetic.main.aibk_include_parent_audioplayer_a.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_answer_view.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_assessment.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.view.*
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import kotlinx.android.synthetic.main.aibk_fragment_mark_model_splitlayout.view.*
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.text.SimpleDateFormat
import java.util.*

class QuesReviewFragmentPpt(
        val activity: AppCompatActivity,
        val testPaperReviewInfor: TestPaperReviewInfor,
        val index_A: Int,
        val index_B: Int
) : KBaseFragment(), View.OnClickListener {

    private var rootView: View? = null
    private val mViewModel: MarkViewModel by viewModel()
    private var isAddView = false
    private var childIndex = 0
    private var jumpSortIndex = ""
    private var isHandSelf = true  //手动滑动
    private var scale = 0f
    private var current_Y = 0
    private var last_Y = 0
    private var fragmentList: MutableList<Fragment>? = ArrayList()

    override fun createLayout(): Int {
        return R.layout.aibk_fragment_model_splitlayout
    }

    override fun initView(view: View?) {
        scale = resources.displayMetrics.density
        rootView = view
        rootView!!.RlArticleView.visibility = View.GONE
        rootView!!.IvPlayOrPause.setOnClickListener(this)
        rootView!!.IBtnArticle.setOnClickListener(this)

        //显示倍速选择功能
        rootView!!.RlPlayerSpeed.visibility = View.VISIBLE
        rootView!!.RvPlayerSpeed.visibility = View.GONE
        val lp: RelativeLayout.LayoutParams
                = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(0, 0, DensityUtils.dp2px(activity,74f), 0)
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);//右对齐
        rootView!!.IvArrowUp.layoutParams = lp

        val audioSpeed = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].AudioSpeed
        //加载倍速选择下拉弹框
        var manager = LinearLayoutManager(activity)
        manager.orientation = LinearLayoutManager.VERTICAL
        rootView!!.RvPlayerSpeed.layoutManager = manager
        val mAdapter = PlayerSpeedChoiceAdapter(activity, audioSpeed,index_A,index_B)
        mAdapter.setClickListener(object : PlayerSpeedChoiceAdapter.OnClickListener{
            override fun onClick(playerSpeed:Double) {
                rootView!!.TvPlayerSpeed.text = playerSpeed.toString()+"x"
                rootView!!.RvPlayerSpeed.visibility = View.GONE
                val drawable = activity.resources.getDrawable(R.mipmap.aibk_icon_player_speed_open)
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                rootView!!.TvPlayerSpeed.setCompoundDrawables(null, null, drawable, null)

                testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].AudioSpeed = playerSpeed
                //此处实现改变音频倍速
                val paperId = testPaperReviewInfor.PaperID
                val quesId = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].QuesID
                adjustAudioSpeedHelp.adjustAudioSpeed(activity,mViewModel,playerSpeed,paperId,quesId)
            }
        })
        rootView!!.RvPlayerSpeed.adapter = mAdapter
        rootView!!.TvPlayerSpeed.text = audioSpeed.toString()+"x"
        rootView!!.RlBtnPlayerSpeed.setOnClickListener{
            if(rootView!!.RvPlayerSpeed.visibility == View.VISIBLE){
                rootView!!.RvPlayerSpeed.visibility = View.GONE
                val drawable = activity.resources.getDrawable(R.mipmap.aibk_icon_player_speed_open)
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                rootView!!.TvPlayerSpeed.setCompoundDrawables(null, null, drawable, null)
            }else{
                rootView!!.RvPlayerSpeed.visibility = View.VISIBLE
                val drawable = activity.resources.getDrawable(R.mipmap.aibk_icon_player_speed_close)
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                rootView!!.TvPlayerSpeed.setCompoundDrawables(null, null, drawable, null)
            }
        }

        showQuestionView()
    }

    /*
    * 显示试题内容
    * */

    private fun showQuestionView() {

        //是否显示来源
        var resource = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].Resource
        if (resource.isEmpty()) {
            rootView!!.IncludeQuesInformationView.visibility = View.GONE
        } else {
            rootView!!.IncludeQuesInformationView.visibility = View.VISIBLE
            rootView!!.IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
            //隐藏试题准确率
            rootView!!.IncludeQuesInformationView.TvScoreRate.visibility = View.GONE
        }

        //加载单题评估系数
        showEvaluationCoefficient()
        //加载题干内容
        var ask = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].QuesBody
        val childListSize = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
        for (c in 0 until childListSize) {
            val childAsk = getChildListBean(testPaperReviewInfor, index_A, index_B, c).ChildAsk
            ask += childAsk
        }
        ask = ask.replace("clickFunction", "Android.clickFunction")

        val typeNo = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].TypeNo
        if (typeNo == "x") {//x:听力匹配
            rootView!!.RlAudioPlayer.visibility = View.VISIBLE
            var timeLength = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.TimeLength
            val format = SimpleDateFormat("mm:ss", Locale.CHINA)
            rootView!!.TvAudioTotalTime.text = format.format(timeLength * 1000)
            var article = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.Article
            if (article.isEmpty()) {
                article = activity.getString(R.string.aibk_no_article)
            } else {
                article = activity.resources.getString(R.string.aibk_yes_article, article)
            }

            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvArticle, article, false)
            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, false)
        } else {
            rootView!!.RlAudioPlayer.visibility = View.GONE
            if (WebStyleUtils.hasTable(ask)) {
                WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, false)
            } else {
                WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, true)
            }
        }
        rootView!!.WvAsk.addJavascriptInterface(
                JSInterface(
                        activity,
                        WebStyleUtils.returnImageUrlsFromHtml(ask)
                ), "Android"
        )

        rootView!!.WvAsk.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                rootView!!.RlWebLoading.visibility = View.GONE
                WebStyleUtils.setWebImageClick(view, "Android")

                isAddView = true
                handler.sendEmptyMessageDelayed(0,100)
            }
        }


        rootView!!.WvAsk.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达地端")
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达顶端")
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "=======oldt========$oldt")
                last_Y = oldt
            }
        })
        //加载作答区域
        fragmentList!!.clear()
        for(c in 0 until childListSize) {
            (fragmentList as ArrayList<Fragment>).add(QuesReviewFragmentParentPpt(activity, testPaperReviewInfor, index_A, index_B, c))
        }
        val mAdapter = KBaseFragmentPagerAdapter(childFragmentManager, fragmentList as ArrayList<Fragment>)
        rootView!!.VpAnswer.adapter = mAdapter
        rootView!!.VpAnswer.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                if (isHandSelf) {
                    childIndex = position
                    showChildVpInfor()
                    jumpSortIndex = getChildListBean(testPaperReviewInfor, index_A, index_B, childIndex).ItemList[0].ItemSortIndex
                    Handler().postDelayed({
                        showBlankView()
                    }, 500)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })

    }

    private fun showChildVpInfor() {
//        val itemListSize = getChildListBean(testPaperReviewInfor,index_A,index_B,0).ItemList.size
//        val itemSortIndexFirst = getChildListBean(testPaperReviewInfor,index_A,index_B,0).ItemList[0].ItemSortIndex
//        val itemSortIndexLast = getChildListBean(testPaperReviewInfor,index_A,index_B,0).ItemList[itemListSize-1].ItemSortIndex
//        rootView!!.TvChildAnswerCount.text = Html.fromHtml(resources.getString(R.string.aibk_ppt_child_count, itemListSize,itemSortIndexFirst,itemSortIndexLast))
        rootView!!.TvChildAnswerCount.text = "从下面选项中挑合适的选项"
        rootView!!.TvChildAnswerCurrent.visibility = View.GONE
    }


    //JS点击事件处理
    inner class JSInterface(var context: Context, var imageUrls: Array<String>?) {

        @JavascriptInterface
        fun clickFunction(position: String) {
            activity.runOnUiThread {
                //在webview中进行点击选择需要作答的区间
                jumpSortIndex = position
                handler.sendEmptyMessageDelayed(0,100)
            }
        }

        //java回调js代码，不要忘了@JavascriptInterface这个注解，不然点击事件不起作用
        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val paths = ArrayList<String>()
            paths.add(img)
            Log.e("openImage", "$pos========点击了图片=========$img")
            ShowDialogTools.showBigImageDialog(activity, img)
        }
    }

    private fun showBlankView() {

        var kWvHeight = rootView!!.WvAsk.height//获取当前webview控件的高度
        rootView!!.WvAsk.evaluateJavascript(
                "javascript:topHeight('blank$jumpSortIndex')",
                ValueCallback<String?> { value ->
                    val dp = Integer.valueOf(value!!)
                    current_Y = (Math.round(dp * scale) - kWvHeight / 2).toInt()//此处关键，保持被点击的区域处于可见区域中间位置
                    val anim: ObjectAnimator =
                            ObjectAnimator.ofInt(
                                    rootView!!.WvAsk, "scrollY", last_Y, current_Y
                            )
                    anim.setDuration(500).start()
                    last_Y = current_Y
                })

        val childListSize = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
        for(c in 0 until childListSize) {
            val itemListSize = getChildListBean(testPaperReviewInfor, index_A, index_B, c).ItemList.size
            for (d in 0 until itemListSize) {
                val itemSortIndex = getChildListBean(testPaperReviewInfor, index_A, index_B, c).ItemList[d].ItemSortIndex
                val itemAnswer = getChildListBean(testPaperReviewInfor, index_A, index_B, c).ItemList[d].ItemAnswer

                if (itemSortIndex == jumpSortIndex) {
                    rootView!!.WvAsk.loadUrl("javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                            "','" + "#ceebff" + "','" + "5px" + "','" + "0px solid #ffffff" + "')")
                } else {
                    rootView!!.WvAsk.loadUrl("javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                            "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #848484" + "')")
                }
                showBlankItemAnswer(itemSortIndex, itemAnswer)
            }
        }
    }

    private fun showBlankItemAnswer(
            itemSortIndex: String,
            itemAnswer: String?
    ) {
        rootView!!.WvAsk.loadUrl(
                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                        + "','" + "&nbsp&nbsp&nbsp&nbsp&nbsp"
                        + "<font color=\"#00b30d\">" + itemAnswer + "</font>"
                        + "&nbsp&nbsp&nbsp&nbsp&nbsp" + " ')"
        )
    }

    //显示评估系数
    private fun showEvaluationCoefficient() {
        rootView!!.TvNanDu.text = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].HVAL
        rootView!!.TvQuFenDu.text = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].DVAL
        rootView!!.TvBaoGuangDu.text = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].EXVAL
    }

    //点击事件
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.IvPlayOrPause -> {
                var quesAudioPath = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.Path
                audioPlayer = AudioPlayer(
                        activity, rootView!!.IvPlayOrPause,
                        rootView!!.SeekBarProgress,
                        rootView!!.TvAudioCurrentTime,
                        rootView!!.TvAudioTotalTime,
                        quesAudioPath,
                        AudioPlayer.ParentAudioListener {
                            val audioSpeed = testPaperReviewInfor.TypeList[index_A].QuesDetailList[index_B].AudioSpeed
                            audioPlayer!!.setPlaySpeed(audioSpeed.toFloat())
                        })
            }
            R.id.IBtnArticle -> {
                if (rootView!!.RlArticleView.visibility == View.GONE) {
                    rootView!!.IBtnArticle.setImageResource(R.mipmap.aibk_audioplayer_article_close)
                    LancooAnim.expand(rootView!!.RlArticleView)
                } else {
                    rootView!!.IBtnArticle.setImageResource(R.mipmap.aibk_audioplayer_article_open)
                    LancooAnim.collapse(rootView!!.RlArticleView)
                }
            }
        }
    }

    fun fragmentJumpToSortIndex(itemSortIndex: String) {
        jumpSortIndex = itemSortIndex
        if(isAddView) {
            handler.sendEmptyMessageDelayed(0, 100)
        }
    }

    //答题卡跳转辅助方法
    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0 -> {
                if (jumpSortIndex.isEmpty()) {//防止初始化为空
                    childIndex = 0
                    jumpSortIndex = getChildListBean(testPaperReviewInfor, index_A, index_B, 0).ItemList[0].ItemSortIndex
                }
                childIndex = QuesReviewInforIndexHelp.SortIndex_return_IndexC(testPaperReviewInfor!!, jumpSortIndex)
                showBlankView()
                showChildVpInfor()
                isHandSelf = false
                rootView!!.VpAnswer.currentItem = childIndex
                Handler().postDelayed({
                    isHandSelf = true
                }, 100)
            }
        }
        false
    })

    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        pauseAudio()
    }

}